<template>
  <div class="resource">

    <el-form v-if="useUserStore().rolesName == '管理组'" ref="ruleFormRef" :model="options" label-width="auto" status-icon>
      <el-row>
        <el-col :span="6">
          <el-form-item style="margin-right: 20px;" label="专业分类" prop="major">
            <el-select v-model="options.marjor_id" placeholder="请选择专业" clearable>
              <el-option v-for="item in majorListData" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item style="margin-right: 20px;" label="资源库名称" prop="name">
            <el-input v-model.trim="options.name" placeholder="请输入名称" clearable />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item>
            <el-button :icon="Search" type="primary" @click="onSearch">
              搜索
            </el-button>

          </el-form-item>
        </el-col>

      </el-row>
    </el-form>


    <el-row v-if="useUserStore().rolesName == '管理组'" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-upload v-model:file-list="JSONfileList" action="" :limit="1" :on-exceed="handleExceed"
          :show-file-list="false" @on-change="JSONuploadChange" :auto-upload="false" accept=".json" ref="JSONuploadRef">
          <el-button type="primary" plain icon="Plus">导入新资源</el-button>
        </el-upload>
      </el-col>
      <el-col :span="1.5" v-if="JSONfileList.length">
        <el-button :icon="Upload" type="success" plain @click="handleUpload">上传</el-button>
      </el-col>


    </el-row>


    <div class="resourceCon">
      <el-table :data="listData" @selection-change="handleSelectionChange">
        <el-table-column label="名称" align="center" prop="name" min-width="8%" />
        <el-table-column label="缩略图" align="center" prop="cover_url" min-width="6%">
          <template #default="scope">
            <div style="display: flex; align-items: center; padding: 10px 0; justify-content: center;">
              <el-image style="width: 80px; height: 40px;" :src="scope.row.cover_url" />
            </div>
          </template>

        </el-table-column>

        <el-table-column label="专业方向" align="center" prop="marjor_name" min-width="8%" />

        <el-table-column label="创建人" align="center" prop="create_name" min-width="6%" />

        <el-table-column label="章节数" align="center" prop="num" min-width="8%">
          <template #default="scope">
            <div class="chapter_count">
              {{ scope.row.chapter_count }} / {{ scope.row.lesson_count }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" min-width="8%" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-dropdown @command="dropdownChange($event, scope.row)" trigger="click">
              <span class="el-dropdown-link">
                更多
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="preview">预览资源</el-dropdown-item>
                  <el-dropdown-item command="copy">拷贝至班课</el-dropdown-item>
                  <el-dropdown-item command="insert" v-if="importJSONarrs.some(item => item.bk_id == scope.row.id)&& useUserStore().rolesName == '管理组'">
                    插入资源
                  </el-dropdown-item>
                  <el-dropdown-item v-if="useUserStore().rolesName == '管理组'" command="delete">删除资源</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

          </template>
        </el-table-column>
      </el-table>
    </div>


    <!-- 分页查询 -->
    <div class='pagelist'>
      <el-pagination hide-on-single-page :current-page='options.page_num' @current-change='currentChange' background
        layout='prev, pager, next' :total='pageTotal' :page-size='options.page_size' />
    </div>




    <el-dialog   v-model="insertDialogVisible" title="关联资源" width="600" :close-on-click-modal="false"
      @close="closeInsertDialogVisible" :close-on-press-escape="false">
<div element-loading-text="zip资源包解压中,请稍等..." v-loading="zipFileLoad" >
      <el-scrollbar  :key="`loading-${fileIdArr.length}-${uploadFileList.length}`" :element-loading-text="`资源文件上传中,上传文件进度(${fileIdArr.length}/${uploadFileList.length})`"  v-loading="resLoading" height="200px">
          <el-upload :on-remove="handleRemove" 
            v-model:file-list="uploadFileList" class="upload-demo" action="" multiple  :on-change="handleChange"
            :auto-upload="false">
            <el-button type="primary">选择资源包</el-button>
          </el-upload>
      </el-scrollbar>
    </div>
      <template #footer>
        <div class="dialog-footer">

          <el-button :disabled="disabledBtn" type="primary" @click="upLoadResFile">
            确认上传
          </el-button>
        </div>
      </template>

    </el-dialog>
  </div>
</template>

<script setup>
import { Search, FolderAdd } from '@element-plus/icons-vue'
import { Upload } from '@element-plus/icons-vue'
import { ref } from "vue"

import useUserStore from '@/store/modules/user'
import { useImport, usePagination } from "./hooks.js"
import { resourceData, fileBind, copyToBk } from "@/api/library.js"
import { majorList } from "@/api/banji/classadmin.js"
import { removeClass } from "@/api/banke/class.js"
import { ElMessage} from 'element-plus';
import { arrangeJSON } from "./resource.js"
import { counterStore } from "@/store/modules/counter"
// 文件上传
import {
  getUpldUrl,
  chunkMerge,
  getUpFileUrl,
  saveUpSfile
} from "@/api/minIOupload";
import axios from "axios";
import uploadStore from "@/store/modules/upload";
import { ElLoading } from 'element-plus'
import { watch } from "vue";

const uploadArr = ref([])
const uploadUrls = ref([])
const props = defineProps({
  fileStyle: {
    type: String
  }

})
const fileIdArr = ref([])
const emits = defineEmits(["fileHzm"])
const store = uploadStore();
let currentFileIndex = 0;
const maxSize = 300 * 1024 * 1024;
const chunkSize = 10 * 1024 * 1024;
// 上传并发数
const simultaneousUploads = 3;
let uploadIdInfo = null;
const FileStatus = {
  wait: "等待上传",
  getMd5: "校验MD5",
  uploading: "正在上传",
  success: "上传成功",
  error: "上传错误",
}


// 文件上传 end
const resLoading = ref(false)
const JSONuploadRef = ref(null);
const router = useRouter();
const resBindFile = ref(null)
const insertDialogVisible = ref(false);
const bk_id = ref(null)
const options = ref({
  is_material: true,
  page_size: 10,
  page_num: 1,
  only_for_me:true,
  name: ""
})


// 导入的数据
const importJSONarrs = ref(JSON.parse(sessionStorage.getItem("importJSONarrs") || "[]"))

// 原始数据
const originalJSONarr = ref(JSON.parse(sessionStorage.getItem("originalJSONarr") || "[]"))

//获取资源列表
const getResource = async () => {
  let { list, total_count, total_pages } = await resourceData(options.value);
  console.log(list);
  listData.value = list;
  pageTotal.value = total_count;

  // 导入的数据
  importJSONarrs.value = JSON.parse(sessionStorage.getItem("importJSONarrs") || "[]")

  // 原始数据
  originalJSONarr.value = JSON.parse(sessionStorage.getItem("originalJSONarr") || "[]")

}


const { handleImport, JSONuploadChange, JSONfileList, uploadFileList, handleUpload, handleChange, disabledBtn,zipFileLoad } = useImport(getResource);


const { currentChange, pageTotal } = usePagination(options, getResource);


const listData = ref([])
const majorListData = ref([])

// 专业列表
const majorData = () => {
  majorList().then(res => {
    majorListData.value = res
  })
}


const handleSelectionChange = () => {

}

const dropdownChange = (e, item) => {

  // 插入资源的逻辑
  if (e == 'insert') {
    // 初始化上传数据
    initUploadFile()
    fileIdArr.value = []

    insertDialogVisible.value = true;
    let find = importJSONarrs.value.find(find => find.bk_id == item.id);
    bk_id.value = find.bk_id
    let listItem = listData.value.find(find => find.id == item.id);

    let original = originalJSONarr.value.find(item => {
      let data = JSON.parse(item.original__data);

      if (data.resource.major == listItem.marjor_name && data.resource.name == listItem.name) return true;
      return false;
    })
    // original.original__data = JSON.parse(original.original__data);
    // 插入资源，调用方法编排json  --- 构造原始数据和保存到cgclass里面后的两端的数据对应关系
    resBindFile.value = arrangeJSON(find, original)
    console.log(resBindFile.value);

  }
  // 预览资源
  if (e == 'preview') {
    console.log(item);
    counterStore().bkItem = item
    router.push({ path: '/designclass', query: { activeNum: 1 } })
  }

  // 拷贝资源至班课
  if (e == 'copy') {
    console.log(item);
    const loading = ElLoading.service({
      lock: true,
      text: '资源库拷贝中,请稍等',
      background: 'rgba(255, 255, 255 0.7)',
    })
    copyToBk(item.id).then(res => {
      console.log(res);
      if(res){
        ElMessage.success("拷贝成功")
        loading.close()
      }else{
        ElMessage.error(res.response.data)
      }ElMessage.error(res.respones.data)
    })
  }
  //删除资源
  if(e=='delete'){

      removeClass(item.id).then(res=>{
        if (!res) {
        ElMessage.success('删除成功');
        getResource();

        }else{
          ElMessage.error(res.response.data);
        }
        
      })

  }

}
const handleExceed = (files) => {
  JSONfileList.value[0].raw = files[0];
}

const onSearch = () => {
  getResource();
}

getResource();
majorData();


//************************* */ 文件上传逻辑开始*****************************

// 关闭对话框取消上传初始化上传数组
const closeInsertDialogVisible = () => {
  initUploadFile()
}

//点击确认或者取消初始化上次数组
const initUploadFile = () => {
  store.setUploadFileList([]);
};

//确认上传资源文件
const upLoadResFile = () => {
  disabledBtn.value = true
  resLoading.value = true
  uploadFileList.value.forEach(item => {
    initFileProperties(item)
  })
  const files = uploadFileList.value;
  if (files.findIndex((fileItem) => fileItem.size < 1) > -1)
    return ElMessage("存在空文件，请删除");
  let bool = files.some((item) => {
    return item.status == "正在上传" || item.status == "校验MD5";
  });

  if (bool) return ElMessage.warning("队列中有正在上传的文件，请稍后~~");

  let successBool = files.every((item) => {
    return item.status == "上传成功";
  });

  if (successBool)
    return ElMessage.warning("上传任务已全部完成，请勿重复上传~~");


  /**
   * 文件分片
   */
  const createFileChunk = (file, size = chunkSize) => {
    if (file.size < 1) return ElMessage.warning("不可上传空文件");
    const fileChunkList = [];
    let count = 0;
    while (count < file.size) {
      fileChunkList.push({
        file: file.slice(count, count + size),
      });
      count += size;
    }
    return fileChunkList;
  };


  // 获取大文件文件的urls
  const getFileUploadUrls = (fileParam) => {
    return getUpldUrl(fileParam);
  };


  //获取小文件上传的url方法
  const getSFileUploadUrls = (fileParams) => {
    return getUpFileUrl(fileParams);
  };
  // 当前操作文件
  const currentFile = files[currentFileIndex];
  currentFile.status = FileStatus.getMd5;
  /**
   * 处理即将上传的分片列表，判断是否有已上传的分片，有则从列表中删除
   */
  const processUploadChunkList = (chunkList) => {
    const currentFile = uploadFileList.value[currentFileIndex];
    let chunkUploadedList = currentFile.chunkUploadedList;
    if (
      chunkUploadedList === undefined ||
      chunkUploadedList === null ||
      chunkUploadedList.length === 0
    ) {
      return chunkList;
    }
    //
    for (let i = chunkList.length - 1; i >= 0; i--) {
      const chunkItem = chunkList[i];
      for (let j = 0; j < chunkUploadedList.length; j++) {
        if (chunkItem.chunkNumber === chunkUploadedList[j]) {
          chunkList.splice(i, 1);
          break;
        }
      }
    }
    return chunkList;
  };
  /**
   * 上传
   */
  const uploadChunkBase = (chunkList) => {
    uploadArr.value = []
    let successCount = 0;
    let totalChunks = chunkList.length;
    return new Promise((resolve) => {
      const handler = () => {

        if (chunkList.length) {
          const chunkItem = chunkList.shift();
          if (chunkItem.stop) {
            return;
          }
          // 直接上传二进制，不需要构造 FormData，否则上传后文件损坏
          axios.put(chunkItem.uploadUrl, chunkItem.chunk.file, {
            // 上传进度处理
            onUploadProgress: checkChunkUploadProgress(chunkItem),
            headers: {
              "Content-Type": "application/octet-stream",
            },
          })
            .then((response) => {

              if (response.status === 200) {
                console.log("分片：" + chunkItem.chunkNumber + " 上传成功");
                successCount++;
                // 继续上传下一个分片
                handler();
              } else {
                console.log(
                  "上传失败：" + response.status + "，" + response.statusText
                );
              }
              uploadArr.value.push(response)
            })
            .catch((error) => {
              if (!uploadFileList.value.length) return;
              if (chunkItem.stop) {
                return;
              }
              // 更新状态
              ElMessage.error(
                "分片：" + chunkItem.chunkNumber + " 上传失败" + error
              );
              // throw '结束上传'

              // 重新添加到队列中
              chunkList.push(chunkItem);
              handler();
            });
        }
        if (successCount >= totalChunks) {
          resolve();
        }
      };
      // 并发
      for (let i = 0; i < simultaneousUploads; i++) {
        handler();
      }
    });
  };


  /**
 * 检查分片上传进度
 */
  const checkChunkUploadProgress = (item) => {
    return (p) => {
      item.progress = parseInt(String((p.loaded / p.total) * 100));
      if (item.stop) return;
      updateChunkUploadStatus(item);
    };
  };


  const updateChunkUploadStatus = (item) => {
    if (!uploadFileList.value.length) return;
    let status = FileStatus.uploading;
    let progressStatus = "normal";
    if (item.progress >= 100) {
      status = FileStatus.success;
      progressStatus = "success";
    }
    let chunkIndex = item.chunkNumber - 1;
    let currentChunk =
      uploadFileList.value[currentFileIndex].chunkList[chunkIndex];
    // 修改状态
    currentChunk.status = status;
    currentChunk.progressStatus = progressStatus;
    // 更新状态
    // this.$set(this.uploadFileList.value[currentFileIndex].chunkList, chunkIndex, currentChunk)
    // 获取文件上传进度
    getCurrentFileProgress();
  };

  const getCurrentFileProgress = () => {
    const currentFile = uploadFileList.value[currentFileIndex];
    if (!currentFile || !currentFile.chunkList) {
      return;
    }
    const chunkList = currentFile.chunkList;
    const uploadedSize = chunkList
      .map((item) => item.chunk.file.size * item.progress)
      .reduce((acc, cur) => acc + cur);
    // 计算方式：已上传大小 / 文件总大小
    let progress = parseInt((uploadedSize / currentFile.size).toFixed(2));
    currentFile.uploadProgress = progress;
    // this.$set(this.uploadFileList, currentFileIndex, currentFile)
  };

  // 上传文件步骤  判断文件是否大于5M，大于5M走分片上传，小于走小文件上传
  if (currentFile.size / 1024 / 1024 > 5) {
    // 1.创建分片(10M一个分片,返回blob格式 数组)

    let fileChunks = createFileChunk(currentFile, chunkSize);
    if (!fileChunks) return;
    //  分片上传
    let params = {
      content_length: currentFile.size,
      file_name: currentFile.name,
      mime: null
    }
    // 2、获取上传文件的urls
    getFileUploadUrls(params).then(res => {
      // 当前操作文件的地址
      // 分片数组
      uploadIdInfo = res;
      uploadUrls.value = uploadIdInfo[0];
      if (fileChunks.length !== uploadUrls.value.length) {
        ElMessage.error("文件分片上传地址获取错误");
        return;
      }

      // 分片上传地址没有问题进行下一步
      // 将blob格式的分片添加到当前操作文件中
      fileChunks.map((chunkItem, index) => {
        currentFile.chunkList.push({
          chunkNumber: index + 1,
          chunk: chunkItem,
          uploadUrl: uploadUrls.value[index].url,
          progress: 0,
          status: "—",
        });
      });


      let tempFileChunks = [];
      currentFile.chunkList.forEach((item) => {
        tempFileChunks.push(item);
      });
      currentFile.status = FileStatus.uploading;
      // 处理分片列表，删除已上传的分片
      tempFileChunks = processUploadChunkList(tempFileChunks);
      // 3. 上传
      uploadChunkBase(tempFileChunks);
      watch(uploadArr.value, nv => {
        if (nv.length == uploadUrls.value.length) {
          //   console.log("分片已全部上传");
          // 4. 合并分片
          let options = uploadIdInfo[1];
          mergeFile(options).then(res => {
            if (res.status == "上传成功") {
              currentFile.status = FileStatus.success;
              currentFile.uploadProgress = 100;
              autoNextUpload(uploadFileList.value);
              currentFile.file_id = res.file_id

              fileIdArr.value.push(res.file_id)

              console.log(fileIdArr.value.length);
              console.log(uploadFileList.value.length);

              if (uploadFileList.value.length == fileIdArr.value.length) {
                ElMessage.success("文件已全部上传完毕");
                resLoading.value = false
                insertDialogVisible.value = false
                initUploadFile()
                // 数据转换开始
                function getBusinessType(name) {
                  if (name.includes("material")) return 2;
                  if (name.includes("baseinfo_img")) return 1;
                  if (name.includes("outline_0") || name.includes("outline_notype_no")) return 4;
                  if (
                    name.includes("operation_content") ||
                    name.includes("operation_notype_no")
                  ) {
                    return 3;
                  }
                  return null; // 如果没有匹配项，则返回null
                }

                function getFileType(name, businessType) {
                  if (businessType === 2) {
                    const match = /material_(\d+)_/.exec(name);
                    return match ? parseInt(match[1], 10) : null; // 提取数字并转为整数
                  }
                  if (businessType === 4) {
                    const extension = name.substring(name.lastIndexOf('.'))
                    switch (extension) {
                      case '.mp4': return 0;
                      case '.pdf': return 1;
                      case '.rar': return 2;
                      case '.zip': return 2;
                    }
                  }
                  return null; // 如果没有匹配项，则返回null
                }

                function transformArray(array) {
                  return array.map(item => {
                    const [prefix, uniqueName] = item.name.split('-_-');
                    const businessType = getBusinessType(prefix);
                    console.log();
                    
                    const fileType = getFileType(item.name, businessType);
                    return {
                      name: uniqueName,
                      business_type: businessType,
                      file_type: fileType !== null ? fileType : undefined, // 当fileType为null时设置为undefined以避免添加无效属性
                      uid: item.uid,
                      file_id: item.file_id,
                      type: item.type,
                      size: item.size
                    };
                  });
                }

                const transformedArr = transformArray(uploadFileList.value);
                // 找到每一项中的业务类型等于1的，代表更新班课，向该对象中追加business_id字段
                const findResult = transformedArr.find(item => item.business_type === 1)
                if (findResult) {
                  findResult.business_id = bk_id.value
                }
                Object.keys(resBindFile.value.sections).forEach(key => {
                  const item = resBindFile.value.sections[key];

                  // 将minioInfos转换为JSON字符串
                  item.minioInfos = JSON.parse(item.minioInfos);

                })
                // 这是上传成功的文件列表
                console.log(transformedArr);
                //这是资源库文件的绑定关系
                console.log(resBindFile.value);
                //********************business_id匹配核心函数开始*************

                transformedArr.forEach(item => {
                  console.log(item);
                  const { business_type, name, file_type } = item;

                  // console.log(resBindFile.value.materials);

                  let found = null;
                  let minioInfoFound = null
                  // 解码文件名用于匹配
                  const decodedName = decodeURIComponent(name);
                 
                  switch (business_type) {
                    case 2: // 处理materials（使用对象值遍历）
                    // 根据m.minioInfo.type存不存在选择，存在则多添加一个条件m.minioInfo.type === file_type
                    const exactMatch = Object.values(resBindFile.value.materials).find(m =>
                      decodeURIComponent(m.minioInfo.url).split('/').pop() === decodedName &&
                      (!m.minioInfo.type || m.minioInfo.type === file_type)
);
                    console.log(exactMatch);
                    
                      if (exactMatch) {
                        
                        
                        item.business_id = exactMatch.id;

                      } else {
                        item.business_id = null; // 明确赋值为空
                        // 记录详细错误日志
                        // console.error('文件匹配失败', {
                        //   fileName: decodedName,
                        //   expectedType: file_type,
                        //   existingFiles: Object.values(resBindFile.value.materials)
                        //     .filter(m => decodeURIComponent(m.minioInfo.url).split('/').pop() === decodedName)
                        //     .map(m => ({ id: m.id, type: m.minioInfo.type }))
                        // });
                      }
                      break;

                    case 3: { // 处理operations（使用对象值遍历）
                      const operations = Object.values(resBindFile.value.operations);
                      console.log(operations);

                      const imgRegex = /<img[^>]+src=["']([^"']+)/i;

                      found = operations.find(op => {
                        const match = op.content.match(imgRegex);
                        if (match) {
                          const urlPart = decodeURIComponent(match[1]).split('/').pop();
                          return urlPart === decodedName;
                        }
                        return false;
                      });

                      minioInfoFound = operations.find(op => {
                        return op.minioInfos.length > 0
                      })


                      item.business_id = (minioInfoFound?.id || found?.id) + '' || null;
                      break;
                    }

                    case 4: // 处理section（使用对象值遍历）
                      found = Object.values(resBindFile.value.sections).find(s =>
                        s.minioInfos.some(m =>
                          decodeURIComponent(m.url).split('/').pop() === decodedName
                        )
                      );
                      item.original_id = found?.original_id + '' || null;
                      // 使用 Object.entries 获取键值对数组
                      const foundEntry = Object.entries(resBindFile.value.sections).find(([key, section]) =>
                        section.minioInfos.some(m =>
                          decodeURIComponent(m.url).split('/').pop() === decodedName

                        )
                      );

                      // 解构赋值获取键名
                      const [foundKey] = foundEntry || [null];

                      // 设置 business_id（保持原有逻辑类型一致性）
                      item.business_id = foundKey ? foundKey.toString() : null;
                      break;

                    default:
                      item.business_id = bk_id.value;
                  }
                });

                // 转换大纲绑定的file_id等于绑定资料的business_id业务逻辑
                // 创建一个映射，存储 business_type 为 2 的项的 business_id
                // bug:如果是分包上传则找不到business_type等于2的
                console.log(transformedArr);
                const businessType2Map = transformedArr
                  .filter(item => item.business_type === 2) // 筛选 business_type 为 2 的项
                  .reduce((map, item) => {
                    const key = `${item.name}-${item.file_type}`; // 使用 name 和 file_type 作为键
                    map[key] = item.business_id;
                    return map;
                  }, {});

                // 遍历 transformedArr，更新 business_type 为 4 的项的 file_id
                // 最终转换
                const resfileBindArr = transformedArr.map(item => {
          
                  if (item.business_type === 4) {
                    const key = `${item.name}-${item.file_type}`; // 使用 name 和 file_type 作为键
                    if (businessType2Map[key]) {
                      // 如果找到匹配项，替换 file_id
                      return {
                        ...item,
                        file_id: businessType2Map[key]
                      };
                    }
                  }
                  // 如果不是 business_type 为 4 的项，或者没有找到匹配项，返回原对象
                  return item;
                });

                console.log(resfileBindArr);


                // 遍历上传的文件调用文件绑定接口更新数据
                const promises = resfileBindArr
                  .filter(item => item.business_id !== null) // 过滤掉 business_id 为 null 的项
                  .map(item => {
                    const options = {
                      file_id: item.file_id,
                      business_id: String(item.business_id),
                      business_type: String(item.business_type),
                      file_type: item.file_type
                    };
                    return fileBind(options);
                  });

                Promise.all(promises)
                  .then(results => {
                    console.log('全部完成', results);
                    // 这里执行后续操作
                    getResource()
                  })
                  .catch(error => {
                    getResource()
                    console.error('发生错误', error);
                  });



              }


            } else {
              // 未上传
              console.log("未上传");
            }

          })
        }
      })
    });
  } else {
    // 小文件上传的逻辑
    return new Promise(async (resolve, reject) => {
      // 第一步:获取小文件上传的url
      let params = {
        "original_filename": currentFile.name,
        "content_length": currentFile.size
      }
      let uploadIdInfoResult = await getSFileUploadUrls(params)
      let blob = createFileChunk(currentFile, chunkSize)[0].file;
      //第二步  上传
      let uploadUrl = uploadIdInfoResult[0]
      let uploadId = uploadIdInfoResult[1]

      currentFile.status = FileStatus.uploading;
      if (uploadIdInfoResult.length) {
        // 直接上传二进制，不需要构造 FormData，否则上传后文件损坏
        axios.put(uploadUrl, blob, {
          // 上传进度处理
          headers: {
            'Content-Type': 'application/octet-stream',
          },
        }).then(response => {
          // 第三步 将文件保存到数据库
          saveUpSfile(uploadId).then(result => {
            currentFile.uploadProgress = 100;
            currentFile.status = FileStatus.success;
            // ElMessage.success('上传成功');
            autoNextUpload(uploadFileList.value);
            currentFile.file_id = result
            fileIdArr.value.push(result)
          })
        }).catch(error => {
          console.log("上传失败" + error);
        })

      }

    })



  }
};
//新上传文件初始化
const initFileProperties = (file) => {
  file.chunkList = [];
};

//清空上传列表
const handleRemove = (file, fileList) => {
  uploadFileList.value = fileList;
};



/**
 * 合并文件
 * @param params 请求参数
 */
const mergeFile = (params) => {
  return new Promise((resolve, reject) => {
    chunkMerge(params)
      .then((res) => {
        // console.log(res);

        if (!res) {
          params.status = FileStatus.error;
          params.file_id = res
          resolve(params);
        } else {
          params.status = FileStatus.success;
          params.file_id = res
          resolve(params);
        }
      })
      .catch((error) => {
        ElMessage.error("合并文件失败：" + error);
        params.status = FileStatus.error;
        reject();
      });
  });
};

/**
 * 上传下标偏移
 */
const autoNextUpload = (files) => {
  currentFileIndex++;
  if (currentFileIndex < files.length) {
    upLoadResFile();
  }
};

/**
 * 保存uploadid到缓存
 */
// let arr1 = []
// const saveFileUploadId = (data) => {
//   arr1.push(data)
//   console.log(arr1);
//   console.log(store.uploadFileList)
//   if (arr1.length == store.uploadFileList.length) {
//     store.uploadFileList = store.uploadFileList.map((item, index) => {
//       return { ...item, ...arr1[index] };
//     });
//     console.log(store.uploadFileList);
//     arr1 = []

//   }


// }

watch(
  () => uploadFileList.value,
  (nv) => {
    store.setUploadFileList(nv);
  },
  { deep: true, immediate: true }
);

watch(
  () => zipFileLoad.value,
  (nv) => {
   console.log(nv);
   
  },
  { deep: true, immediate: true }
);

//监听上次列表的数据变化
watch(
  () => store.uploadFileList,
  (nv) => {
    uploadFileList.value = nv;
    if (nv == 0) {
      currentFileIndex = 0;
    }
  }
);

</script>

<style lang="scss" scoped>
.resource {
  padding-top: 30px;
  position: relative;
  z-index: 0;
}

.operate {
  display: flex;
  justify-content: center;
  align-items: center;

  .item {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 15px;
    color: #1890FF;
    cursor: pointer;
    font-size: 14px;
  }
}
</style>
